package org.luxor.storage.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.luxor.commons.core.web.controller.BaseRestController;
import org.luxor.commons.storage.constant.StorageType;
import org.luxor.commons.storage.service.IFileStorageService;
import org.luxor.storage.utils.ParamExtUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.MimeTypeUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
 * OSS防盗链资源下载
 *
 * @author Mr.yan @date 2020/3/29
 */
@RestController
@Api(tags = "OSS防盗链相关")
public class JumpController extends BaseRestController {
    private static final Logger logger = LoggerFactory.getLogger(JumpController.class);

    @Resource
    private IFileStorageService fileStorageService;

    @GetMapping("/jump")
    @PreAuthorize("hasPermission(#request,'sys:storage:jump')")
    @ApiOperation("OSS防盗链安全下载")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "path", paramType = "query", dataType = "String", required = true,
                    value = "文件路径 (如：http://127.0.0.1/sso/images/2020-03-23/background_1_000939920.jpg)")
    })
    public void httpDownload(@RequestParam String path, HttpServletResponse response) {
        String fileFullPath = ParamExtUtils.extFileFullPath(path);
        Integer storageType = ParamExtUtils.extStorageType(fileFullPath);
        String fileFullName = ParamExtUtils.extFileFullName(fileFullPath);
        String mimeType = ParamExtUtils.getMimeType(fileFullName);
        if (MimeTypeUtils.APPLICATION_OCTET_STREAM_VALUE.equals(mimeType)) {
            response.addHeader("Content-Disposition", "attachment; filename=\"" + fileFullName + "\"");
        }
        response.addHeader("Content-Type", mimeType);

        fileStorageService.httpDownload(StorageType.valueOf(storageType), fileFullPath, response);
    }
}
